package com.ruihang.generalibrary.utils;

import android.util.SparseArray;

/**
 * 数据版本管理类，用于本地数据更改的版本管理
 * Created by Administrator on 2017/4/24.
 */

public class DatasVersionManager {
    private static DatasVersionManager instance;

    private SparseArray<DatasVersion> versions;

    private DatasVersionManager() {
        versions = new SparseArray<>();
    }

    public SparseArray<DatasVersion> getVersions() {
        return versions;
    }

    public static DatasVersionManager getInstance() {
        if (instance == null) {
            instance = new DatasVersionManager();
        }
        return instance;
    }

    public static void init() {
        DatasVersionManager dvm = getInstance();
        if (dvm.getVersions().size() > 0) {
            dvm.getVersions().clear();
        }
    }

    public static boolean isVersionDiff(int versionKey, int version) {
        DatasVersionManager dvm = getInstance();
        DatasVersion ver = dvm.getVersions().get(versionKey);
        return ver != null && ver.isVersionDiff(version);
    }

    public static int updateVersion(int versionKey) {
        DatasVersionManager dvm = getInstance();
        DatasVersion ver = dvm.getVersions().get(versionKey);
        if (ver == null) {
            ver = new DatasVersion(versionKey);
            dvm.getVersions().put(versionKey, ver);
            return ver.getVersion();
        } else {
            return ver.updateVersion();
        }
    }

    public static int getVersion(int versionKey) {
        DatasVersion dv = getInstance().getVersions().get(versionKey);
        return dv == null ? -1 : dv.getVersion();
    }

    /**
     * 获取版本号
     * @param versionKey
     * @param isValuedRe 是否强制返回有效值
     * @return
     */
    public static int getVersion(int versionKey,boolean isValuedRe) {
        DatasVersion dv = getInstance().getVersions().get(versionKey);
        if (dv==null){
            dv=new DatasVersion(versionKey);
            getInstance().getVersions().put(versionKey,dv);
        }
        return dv.getVersion();
    }
}
